package com.canal.admin.service.impl;

import com.canal.admin.config.properties.CanalProperties;
import com.canal.admin.dao.ZcolChannelItemMapper;
import com.canal.admin.dao.ZcolChannelMapper;
import com.canal.admin.dao.ZcolRtRegMapper;
import com.canal.admin.entity.canal.ZcolChannel;
import com.canal.admin.entity.canal.ZcolChannelItem;
import com.canal.admin.exception.BuzException;
import com.canal.admin.service.QiniuService;
import com.canal.admin.service.ZcolChannelItemService;
import com.canal.admin.transfer.req.item.ChannelItemAddReq;
import com.canal.admin.transfer.req.item.DiscountSetReq;
import com.canal.admin.transfer.req.item.ItemListConditions;
import com.canal.admin.transfer.req.item.ItemUpReq;
import com.canal.admin.transfer.resp.PageResp;
import com.canal.admin.transfer.resp.canal.ChannelListResp;
import com.canal.admin.transfer.resp.item.ChannelItemListResp;
import com.canal.admin.transfer.resp.item.ItemDetailResp;
import com.canal.admin.util.CodeGenerator;
import com.canal.admin.util.DateUtil;
import com.canal.admin.util.PageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 渠道号服务类
 * @author yangbo
 * @date 2020-06-24 9:03
 */
@Service
@Slf4j
public class ZcolChannelItemServiceImpl implements ZcolChannelItemService {

    @Autowired
    private ZcolChannelMapper channelMapper;

    @Autowired
    private ZcolChannelItemMapper channelItemMapper;

    @Autowired
    private QiniuService qiniuService;

    @Autowired
    private CanalProperties canalProperties;

    @Autowired
    private ZcolRtRegMapper zcolRtRegMapper;

    /**
     * 渠道号列表
     * @param conditions
     * @return
     */
    @Override
    public PageResp<ChannelItemListResp> list(ItemListConditions conditions) {
        PageHelper.startPage(conditions.getPageNo(),conditions.getPageSize());
        List<ChannelItemListResp> itemListResps = channelItemMapper.listByCondition(conditions.getKeyword());
        PageInfo<ChannelItemListResp> pageInfo = new PageInfo<>(itemListResps);
        return PageUtil.toResp(pageInfo);
    }

    /**
     * 渠道号新增
     * @param addReq
     * @throws BuzException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addItem(ChannelItemAddReq addReq) throws BuzException {
        //校验名称重复
        if(channelItemMapper.existByName(addReq.getName()) > 0) {
            throw new BuzException(500,"渠道号重复");
        }
        //组装数据
        ZcolChannelItem channelItem = new ZcolChannelItem();
        channelItem.setChannelId(addReq.getChannelId().longValue());
        channelItem.setName(addReq.getName());
        String code = CodeGenerator.genCode(addReq.getName());
        while(channelItemMapper.existByCode(code) > 0) {
            code = CodeGenerator.genCode(addReq.getName());
        }
        channelItem.setCode(code);
        channelItem.setInputStart(DateUtil.parse(addReq.getInputStart(),"HH:mm:ss"));
        channelItem.setInputEnd(DateUtil.parse(addReq.getInputEnd(),"HH:mm:ss"));
        channelItem.setApkUrl(qiniuService.getUri(addReq.getApkUrl()));
        channelItem.setH5Url("/channel/"+code);
        channelItem.setDiscountRate(addReq.getDiscountRate());
        channelItem.setInputState(addReq.getDiscountState());
        if(!addReq.getDiscountState()) {
            //暂停进量，设置进量暂停时间
            channelItem.setStopTime(new Date());
        }
        channelItem.setUvPrice(addReq.getUvPrice());
        channelItem.setRegPrice(addReq.getRegPrice());
        channelItemMapper.addChannelItem(channelItem);
    }

    /**
     * 设置折扣
     * @param setReq
     * @throws BuzException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setDiscount(DiscountSetReq setReq) throws BuzException {
        ZcolChannelItem zcolChannelItem = new ZcolChannelItem();
        zcolChannelItem.setId(setReq.getId().longValue());
        zcolChannelItem.setDiscountRate(setReq.getRate());
        channelItemMapper.setDiscountRateById(zcolChannelItem);
    }

    /**
     * 设置状态
     * @param id
     * @throws BuzException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setInputState(Integer id) throws BuzException {
        ZcolChannelItem channelItem = channelItemMapper.getChannelItemById(id);
        if(channelItem.getInputState()) {
            channelItem.setInputState(false);
            channelItem.setStopTime(new Date());
        } else {
            channelItem.setInputState(true);
            channelItem.setStopTime(null);
        }
        channelItemMapper.setInputStateById(channelItem);
    }

    /**
     * 批量删除，返回不能删除的渠道号集合
     * @param ids
     * @return
     * @throws BuzException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Integer> batchDel(List<Integer> ids) throws BuzException {
        //删选出能被删除的
        List<Integer> canDelIds = new ArrayList<>(ids.size());
        List<Integer> cantDelIds = new ArrayList<>(ids.size());
        for (Integer id : ids) {
            int count = zcolRtRegMapper.existByChannelItemId(id);
            if(count > 0) {
                cantDelIds.add(id);
            } else {
                canDelIds.add(id);
            }
        }
        if(canDelIds.size() > 0) {
            channelItemMapper.batchDel(canDelIds);
        }
        return cantDelIds;
    }

    /**
     * 详情
     * @param id
     * @return
     */
    @Override
    public ItemDetailResp detail(Integer id) {
        ZcolChannelItem channelItem = channelItemMapper.getChannelItemById(id);
        if(channelItem == null) {
            return null;
        }
        ZcolChannel zcolChannel = channelItem.getZcolChannel();
        ItemDetailResp detailResp = ItemDetailResp.builder()
                .id(channelItem.getId().intValue())
                .name(channelItem.getName())
                .channelId(zcolChannel.getId())
                .channelName(zcolChannel.getName())
                .apkUrl(qiniuService.getUrl(channelItem.getApkUrl()))
                .h5Url(canalProperties.getUrl(channelItem.getH5Url()))
                .discountRate(channelItem.getDiscountRate())
                .discountState(channelItem.getInputState())
                .inputStart(channelItem.getInputStart())
                .inputEnd(channelItem.getInputEnd())
                .uvPrice(channelItem.getUvPrice())
                .regPrice(channelItem.getRegPrice())
                .build();
        return detailResp;
    }

    /**
     * 编辑
     * @param upReq
     * @throws BuzException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ItemUpReq upReq) throws BuzException {
        if(channelItemMapper.existByIdAndName(upReq.getId(),upReq.getName()) > 0) {
            throw new BuzException(500,"渠道号已存在");
        }
        ZcolChannelItem item = new ZcolChannelItem();
        item.setId(upReq.getId().longValue());
        item.setName(upReq.getName());
        item.setApkUrl(qiniuService.getUri(upReq.getApkUrl()));
        item.setUvPrice(upReq.getUvPrice());
        item.setRegPrice(upReq.getRegPrice());
        item.setInputStart(DateUtil.parse(upReq.getInputStart(),"HH:mm:ss"));
        item.setInputEnd(DateUtil.parse(upReq.getInputEnd(),"HH:mm:ss"));
        item.setApkUrl(qiniuService.getUri(upReq.getApkUrl()));
        item.setDiscountRate(upReq.getDiscountRate());
        item.setInputState(upReq.getDiscountState());
        if(upReq.getDiscountState()) {
            item.setStopTime(null);
        } else {
            item.setStopTime(new Date());
        }
        channelItemMapper.updateItem(item);
    }

    @Override
    public List<Map<String, Object>> channelList(String keyword) {
        List<ChannelListResp> channelListResps = channelMapper.findChannelByConditions(keyword);
        List<Map<String,Object>> resultList = new ArrayList<>(channelListResps.size() + 1);
        for (ChannelListResp listResp : channelListResps) {
            Map<String,Object> map = new HashMap<>(4);
            map.put("id",listResp.getId());
            map.put("name",listResp.getName());
            resultList.add(map);
        }
        return resultList;
    }


}
